<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="ES6,reduce,解构," />





  <link rel="alternate" href="/atom.xml" title="I'm Minizh" type="application/atom+xml" />






<meta name="description" content="摘要：总结ES6新特性：默认参数、reduce、解构赋值和Set在使用时的一些小技巧。 ES6出来已经有好几年了，同时很多新特性可以被巧妙地运用在项目中。我想要列下其中一些，希望它们对你有用。     如果你还知道其他一些小技巧，欢迎留言。我很高兴把它们补充进来。 1. 强制要求参数ES6提供了默认参数值机制，允许你为参数设置默认值，防止函数在调用时没有传入这些参数。 在下面的例子中，我们写了一个">
<meta name="keywords" content="ES6,reduce,解构">
<meta property="og:type" content="article">
<meta property="og:title" content="ES6小技巧">
<meta property="og:url" content="http://yoursite.com/2018/10/09/ES6小技巧/index.html">
<meta property="og:site_name" content="I&#39;m Minizh">
<meta property="og:description" content="摘要：总结ES6新特性：默认参数、reduce、解构赋值和Set在使用时的一些小技巧。 ES6出来已经有好几年了，同时很多新特性可以被巧妙地运用在项目中。我想要列下其中一些，希望它们对你有用。     如果你还知道其他一些小技巧，欢迎留言。我很高兴把它们补充进来。 1. 强制要求参数ES6提供了默认参数值机制，允许你为参数设置默认值，防止函数在调用时没有传入这些参数。 在下面的例子中，我们写了一个">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-10-09T11:10:19.137Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ES6小技巧">
<meta name="twitter:description" content="摘要：总结ES6新特性：默认参数、reduce、解构赋值和Set在使用时的一些小技巧。 ES6出来已经有好几年了，同时很多新特性可以被巧妙地运用在项目中。我想要列下其中一些，希望它们对你有用。     如果你还知道其他一些小技巧，欢迎留言。我很高兴把它们补充进来。 1. 强制要求参数ES6提供了默认参数值机制，允许你为参数设置默认值，防止函数在调用时没有传入这些参数。 在下面的例子中，我们写了一个">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Minizh'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/10/09/ES6小技巧/"/>





  <title>ES6小技巧 | I'm Minizh</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta custom-logo">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">I'm Minizh</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">ZH的个人博客</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
        
          
            <li class="menu-item menu-item-categories">
              <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/js/">js</a><span class="category-list-count">5</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/js/ES6/">ES6</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/js/Object-keys/">Object.keys</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/js/js遍历/">js遍历</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/js/异步/">异步</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/">工具类</a><span class="category-list-count">3</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/MarkDown语法/">MarkDown语法</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/Smark/">Smark</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/hexo/">hexo</a><span class="category-list-count">1</span></li></ul></li></ul>
            </li>
          
        
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/atom.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/2018/08/19/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
        
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/10/09/ES6小技巧/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="你就像谜一样">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/1383101481859.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="I'm Minizh">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ES6小技巧</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-09T19:09:10+08:00">
                2018-10-09
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/ES6/" itemprop="url" rel="index">
                    <span itemprop="name">ES6</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><code>摘要：总结ES6新特性：默认参数、reduce、解构赋值和Set在使用时的一些小技巧。</code></p>
<p>ES6出来已经有好几年了，同时很多新特性可以被巧妙地运用在项目中。我想要列下其中一些，希望它们对你有用。    </p>
<p>如果你还知道其他一些小技巧，欢迎留言。我很高兴把它们补充进来。</p>
<h3 id="1-强制要求参数"><a href="#1-强制要求参数" class="headerlink" title="1. 强制要求参数"></a>1. 强制要求参数</h3><p><strong><code>ES6</code></strong>提供了默认参数值机制，允许你为参数设置默认值，防止函数在调用时没有传入这些参数。</p>
<p>在下面的例子中，我们写了一个required()函数作为参数a和b的默认值。<br>这意味着如果a或b其中有一个参数没有在调用时传值，会默认required()函数，然后抛出错误。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">const required = () =&gt; &#123;throw new Error(&apos;Missing parameter&apos;)&#125;;</span><br><span class="line">const add = (a = required(), b = required()) =&gt; a + b;</span><br><span class="line">add(1, 2) //3</span><br><span class="line">add(1) // Error: Missing parameter.</span><br></pre></td></tr></table></figure></p>
<h3 id="2-强大的reduce"><a href="#2-强大的reduce" class="headerlink" title="2. 强大的reduce"></a>2. 强大的reduce</h3><p>数组的reduce方法用途很广。它一般被用来把数组中每一项规约到单个值。但是你可以利用它做更多的事。</p>
<h4 id="2-1-使用reduce同时实现map和filter"><a href="#2-1-使用reduce同时实现map和filter" class="headerlink" title="2.1 使用reduce同时实现map和filter"></a>2.1 使用reduce同时实现map和filter</h4><p>假设现在有一个数列，你希望更新它的每一项（map的功能）然后筛选出一部分（filter的功能）。如果是先使用map然后filter的话，你需要遍历这个数组两次。</p>
<p>在下面的代码中，我们将数列中的值翻倍，然后挑选出那些大于50的数。有注意到我们是如何非常高效地使用reduce来同时完成map和filter方法的吗？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">const numbers = [10, 20, 30, 40];</span><br><span class="line">const doubledOver50 = numbers.reduce((finalList, num) =&gt; &#123;</span><br><span class="line">  </span><br><span class="line">  num = num * 2; </span><br><span class="line">  </span><br><span class="line">  if (num &gt; 50) &#123;</span><br><span class="line">    finalList.push(num);</span><br><span class="line">  &#125;</span><br><span class="line">  return finalList;</span><br><span class="line">&#125;, []);</span><br><span class="line">doubledOver50; // [60, 80]</span><br></pre></td></tr></table></figure>
<p><code>关于reduce参数说明及一些高级操作</code><a href="https://segmentfault.com/a/1190000005921341" title="reduce" target="_blank" rel="noopener">数组reduce方法的高级技巧</a> 。</p>
<h4 id="2-2-使用reduce匹配圆括号"><a href="#2-2-使用reduce匹配圆括号" class="headerlink" title="2.2 使用reduce匹配圆括号"></a>2.2 使用reduce匹配圆括号</h4><p>reduce的另外一个用途是能够匹配给定字符串中的圆括号。对于一个含有圆括号的字符串，我们需要知道(和)的数量是否一致，并且(是否出现在)之前。</p>
<p>下面的代码中我们使用reduce可以轻松地解决这个问题。我们只需要先声明一个counter变量，初值为0。在遇到(时counter加一，遇到)时counter减一。如果左右括号数目匹配，那最终结果为0。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">//Returns 0 if balanced.</span><br><span class="line">const isParensBalanced = (str) =&gt; &#123;</span><br><span class="line">  return str.split(&apos;&apos;).reduce((counter, char) =&gt; &#123;</span><br><span class="line">    if(counter &lt; 0) &#123; //matched &quot;)&quot; before &quot;(&quot;</span><br><span class="line">      return counter;</span><br><span class="line">    &#125; else if(char === &apos;(&apos;) &#123;</span><br><span class="line">      return ++counter;</span><br><span class="line">    &#125; else if(char === &apos;)&apos;) &#123;</span><br><span class="line">      return --counter;</span><br><span class="line">    &#125;  else &#123; //matched some other char</span><br><span class="line">      return counter;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">  &#125;, 0); //&lt;-- starting value of the counter</span><br><span class="line">&#125;</span><br><span class="line">isParensBalanced(&apos;(())&apos;) // 0 &lt;-- balanced</span><br><span class="line">isParensBalanced(&apos;(asdfds)&apos;) //0 &lt;-- balanced</span><br><span class="line">isParensBalanced(&apos;(()&apos;) // 1 &lt;-- not balanced</span><br><span class="line">isParensBalanced(&apos;)(&apos;) // -1 &lt;-- not balanced</span><br></pre></td></tr></table></figure></p>
<h4 id="2-3-统计数组中相同项的个数"><a href="#2-3-统计数组中相同项的个数" class="headerlink" title="2.3 统计数组中相同项的个数"></a>2.3 统计数组中相同项的个数</h4><p>很多时候，你希望统计数组中重复出现项的个数然后用一个对象表示。那么你可以使用reduce方法处理这个数组。</p>
<p>下面的代码将统计每一种车的数目然后把总数用一个对象表示。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var cars = [&apos;BMW&apos;,&apos;Benz&apos;, &apos;Benz&apos;, &apos;Tesla&apos;, &apos;BMW&apos;, &apos;Toyota&apos;];</span><br><span class="line">var carsObj = cars.reduce(function (obj, name) &#123; </span><br><span class="line">   obj[name] = obj[name] ? ++obj[name] : 1;</span><br><span class="line">  return obj;</span><br><span class="line">&#125;, &#123;&#125;);</span><br><span class="line">carsObj; // =&gt; &#123; BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 &#125;</span><br><span class="line">reduce的其他用处实在是太多了，我建议你阅读MDN的相关代码示例。</span><br></pre></td></tr></table></figure></p>
<h3 id="3-对象解构"><a href="#3-对象解构" class="headerlink" title="3. 对象解构"></a>3. 对象解构</h3><h4 id="3-1-删除不需要的属性"><a href="#3-1-删除不需要的属性" class="headerlink" title="3.1 删除不需要的属性"></a>3.1 删除不需要的属性</h4><p>有时候你不希望保留某些对象属性，也许是因为它们包含敏感信息或仅仅是太大了（just too big）。你可能会枚举整个对象然后删除它们，但实际上只需要简单的将这些无用属性赋值给变量，然后把想要保留的有用部分作为剩余参数就可以了。</p>
<p>下面的代码里，我们希望删除_internal和tooBig参数。我们可以把它们赋值给internal和tooBig变量，然后在cleanObject中存储剩下的属性以备后用。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">let &#123;_internal, tooBig, ...cleanObject&#125; = &#123;el1: &apos;1&apos;, _internal:&quot;secret&quot;, tooBig:&#123;&#125;, el2: &apos;2&apos;, el3: &apos;3&apos;&#125;;</span><br><span class="line">console.log(cleanObject); // &#123;el1: &apos;1&apos;, el2: &apos;2&apos;, el3: &apos;3&apos;&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="3-2-在函数参数中解构嵌套对象"><a href="#3-2-在函数参数中解构嵌套对象" class="headerlink" title="3.2 在函数参数中解构嵌套对象"></a>3.2 在函数参数中解构嵌套对象</h4><p>在下面的代码中，engine是对象car中嵌套的一个对象。如果我们对engine的vin属性感兴趣，使用解构赋值可以很轻松地得到它。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">var car = &#123;</span><br><span class="line">  model: &apos;bmw 2018&apos;,</span><br><span class="line">  engine: &#123;</span><br><span class="line">    v6: true,</span><br><span class="line">    turbo: true,</span><br><span class="line">    vin: 12345</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">const modelAndVIN = (&#123;model, engine: &#123;vin&#125;&#125;) =&gt; &#123;</span><br><span class="line">  console.log(`model: $&#123;model&#125; vin: $&#123;vin&#125;`);</span><br><span class="line">&#125;</span><br><span class="line">modelAndVIN(car); // =&gt; model: bmw 2018  vin: 12345</span><br></pre></td></tr></table></figure></p>
<h4 id="3-3-合并对象"><a href="#3-3-合并对象" class="headerlink" title="3.3 合并对象"></a>3.3 合并对象</h4><p>ES6带来了扩展运算符（…）。它一般被用来解构数组，但你也可以用它处理对象。</p>
<p>接下来，我们使用扩展运算符来展开一个新的对象，第二个对象中的属性值会改写第一个对象的属性值。比如object2的b和c就会改写object1的同名属性。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">let object1 = &#123; a:1, b:2,c:3 &#125;</span><br><span class="line">let object2 = &#123; b:30, c:40, d:50&#125;</span><br><span class="line">let merged = &#123;…object1, …object2&#125; //spread and re-add into merged</span><br><span class="line">console.log(merged) // &#123;a:1, b:30, c:40, d:50&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="4-Sets"><a href="#4-Sets" class="headerlink" title="4. Sets"></a>4. Sets</h3><h4 id="4-1-使用Set实现数组去重"><a href="#4-1-使用Set实现数组去重" class="headerlink" title="4.1 使用Set实现数组去重"></a>4.1 使用Set实现数组去重</h4><p>在ES6中，因为Set只存储唯一值，所以你可以使用Set删除重复项。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">let arr = [1, 1, 2, 2, 3, 3];</span><br><span class="line">let deduped = [...new Set(arr)] // [1, 2, 3]</span><br></pre></td></tr></table></figure></p>
<h4 id="4-2-对Set使用数组方法"><a href="#4-2-对Set使用数组方法" class="headerlink" title="4.2 对Set使用数组方法"></a>4.2 对Set使用数组方法</h4><p>使用扩展运算符就可以简单的将Set转换为数组。所以你可以对Set使用Array的所有原生方法。</p>
<p>比如我们想要对下面的Set进行filter操作，获取大于3的项。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">let mySet = new Set([1,2, 3, 4, 5]);</span><br><span class="line">var filtered = [...mySet].filter((x) =&gt; x &gt; 3) // [4, 5]</span><br></pre></td></tr></table></figure></p>
<h3 id="5-数组解构"><a href="#5-数组解构" class="headerlink" title="5. 数组解构"></a>5. 数组解构</h3><p>有时候你会将函数返回的多个值放在一个数组里。我们可以使用数组解构来获取其中每一个值。</p>
<h4 id="5-1-数值交换"><a href="#5-1-数值交换" class="headerlink" title="5.1 数值交换"></a>5.1 数值交换</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">let param1 = 1;</span><br><span class="line">let param2 = 2;</span><br><span class="line">//swap and assign param1 &amp; param2 each others values</span><br><span class="line">[param1, param2] = [param2, param1];</span><br><span class="line">console.log(param1) // 2</span><br><span class="line">console.log(param2) // 1</span><br></pre></td></tr></table></figure>
<h4 id="5-2-接收函数返回的多个结果"><a href="#5-2-接收函数返回的多个结果" class="headerlink" title="5.2 接收函数返回的多个结果"></a>5.2 接收函数返回的多个结果</h4><p>在下面的代码中，我们从/post中获取一个帖子，然后在/comments中获取相关评论。由于我们使用的是async/await，函数把返回值放在一个数组中。而我们使用数组解构后就可以把返回值直接赋给相应的变量。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">async function getFullPost()&#123;</span><br><span class="line">  return await Promise.all([</span><br><span class="line">    fetch(&apos;/post&apos;),</span><br><span class="line">    fetch(&apos;/comments&apos;)</span><br><span class="line">  ]);</span><br><span class="line">&#125;</span><br><span class="line">const [post, comments] = getFullPost();</span><br></pre></td></tr></table></figure></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ES6/" rel="tag"># ES6</a>
          
            <a href="/tags/reduce/" rel="tag"># reduce</a>
          
            <a href="/tags/解构/" rel="tag"># 解构</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/05/async-await/" rel="next" title="ES7 异步神器 async-await">
                <i class="fa fa-chevron-left"></i> ES7 异步神器 async-await
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODk1Ni8xNTQ4NA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/1383101481859.jpg"
                alt="你就像谜一样" />
            
              <p class="site-author-name" itemprop="name">你就像谜一样</p>
              <p class="site-description motion-element" itemprop="description">Stay foolish, Stay hungry</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yourname" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:yourname@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/yourname" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/yourname" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.facebook.com/yourname" target="_blank" title="FB Page">
                      
                        <i class="fa fa-fw fa-facebook"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://stackoverflow.com/yourname" target="_blank" title="StackOverflow">
                      
                        <i class="fa fa-fw fa-stack-overflow"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://youtube.com/yourname" target="_blank" title="YouTube">
                      
                        <i class="fa fa-fw fa-youtube"></i></a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://segmentfault.com/" title="segmentfault" target="_blank">segmentfault</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-强制要求参数"><span class="nav-number">1.</span> <span class="nav-text">1. 强制要求参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-强大的reduce"><span class="nav-number">2.</span> <span class="nav-text">2. 强大的reduce</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-使用reduce同时实现map和filter"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 使用reduce同时实现map和filter</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-使用reduce匹配圆括号"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 使用reduce匹配圆括号</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-统计数组中相同项的个数"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 统计数组中相同项的个数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-对象解构"><span class="nav-number">3.</span> <span class="nav-text">3. 对象解构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-删除不需要的属性"><span class="nav-number">3.1.</span> <span class="nav-text">3.1 删除不需要的属性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-在函数参数中解构嵌套对象"><span class="nav-number">3.2.</span> <span class="nav-text">3.2 在函数参数中解构嵌套对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-合并对象"><span class="nav-number">3.3.</span> <span class="nav-text">3.3 合并对象</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-Sets"><span class="nav-number">4.</span> <span class="nav-text">4. Sets</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-使用Set实现数组去重"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 使用Set实现数组去重</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-对Set使用数组方法"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 对Set使用数组方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-数组解构"><span class="nav-number">5.</span> <span class="nav-text">5. 数组解构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-数值交换"><span class="nav-number">5.1.</span> <span class="nav-text">5.1 数值交换</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-接收函数返回的多个结果"><span class="nav-number">5.2.</span> <span class="nav-text">5.2 接收函数返回的多个结果</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">你就像谜一样</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  

  

  

</body>
</html>
